home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2789 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.7 KB

  1. Path: charnel.ecst.csuchico.edu!mcelroy
  2. From: mcelroy@ecst.csuchico.edu (James Robert McElroy)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Virtual Members: Difficult Question
  5. Date: 19 Jan 1996 18:38:33 GMT
  6. Organization: California State University, Chico
  7. Message-ID: <4doof9$hom@charnel.ecst.csuchico.edu>
  8. References: <4dmha6$80c@marlin.ssnet.com>
  9. NNTP-Posting-Host: hairball.ecst.csuchico.edu
  10.  
  11. A general comment about your code:
  12.  
  13. You are casting the wrong way in the inheritance hierarchy.
  14. This is guaranteed to blow up at some point, often unpredic-
  15. tably.  Some times it will work, some times it won't (similar
  16. to driving the wrong way down a one-way street).
  17.  
  18. Look at it this way:  in terms of physical space taken up by
  19. a class object, a base class object will always take up less room than 
  20. a derived class object, right?  Now, if you tell a base class object it is
  21. actually a derived class object (via the cast) the pointer now thinks
  22. it has more room in memory than it actually does.  
  23.  
  24. Let's say the base class object takes up 20
  25. bytes.  Now, by definition, the derived class object must take up
  26. the same or more room, because it, in essence, contains the
  27. base class object.  Let's say you have a derived class object that
  28. takes 28 bytes of memery.  So you cast a base class object to the
  29. derived class object pointer, and if you start messing around with bytes
  30. 21-28 via the pointer, you are tampering with memory that isn't yours!
  31.  
  32. Look at it this way -- would the following code cause  problems?
  33.  
  34. int foo;
  35. long * fubar = (long*)&foo;
  36. *fubar = 10;        // gee, no problem here
  37. *fubar = 32468551;  // uh oh.  Seems to crash.  Don't know why!
  38.  
  39. Yup.  Similar to what you are experiencing. 
  40.  
  41. -- 
  42. Jim McElroy
  43. Calif. State Univ., Chico
  44. mcelroy@ecst.csuchico.edu
  45.